import React, {useEffect, useState} from 'react';
import {Avatar, Button, Card, Empty, message, Modal, Select, Space, Upload} from "antd";
import {InboxOutlined, UserOutlined} from '@ant-design/icons';
import classes from './index.module.scss'
import {useSelector} from "react-redux";
import {getToken} from "../../../utils/token";
import {reqDownLoadFile, reqGetFiles, reqSaveFiles} from "../../../api/frontDesk/frontDeskApi";
import LoginAlert from "../../../component/LoginAlert";

const {Dragger} = Upload


const typeList = [
    {key: 1, value: '全部', label: '全部'},
    {key: 2, value: '前端', label: '前端'},
    {key: 3, value: '后端', label: '后端'},
    {key: 4, value: 'Android', label: 'Android'},
    {key: 5, value: '代码人生', label: '代码人生'},
    {key: 6, value: '人工智能', label: '人工智能'},
    {key: 7, value: 'IOS', label: 'IOS'},
    {key: 8, value: '阅读', label: '阅读'},
    {key: 9, value: '开发工具', label: '开发工具'},

]

const MyDownLoad = () => {

    //http://127.0.0.1:8081/images/user_avatar/4-hO-lcocl9fk1RdhMpFZGkq.png
    const apiUrl=`${process.env.REACT_APP_API_URL}/images/user_avatar/4-hO-lcocl9fk1RdhMpFZGkq.png`
    const [open, setOpen] = useState(false);
    const [loginOpen, setLoginOpen] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [isDownloading, setIsDownloading] = useState(false);
    const [fileList, setFileList] = useState([])
    const [uploadFileList, setUploadFileList] = useState([])
    const [isClick, setIsClick] = useState('全部')
    const [typeIsClick, setTypeIsClick] = useState('全部')
    const [downloadOpen, setDownLoadOpen] = useState(false)
    const [sortValue, setSortValue] = useState('全部')

    const {userAllInfo} = useSelector((state) => state.persistedReducer.user)


    useEffect(() => {
        getData()
    }, [])
    const getData = async () => {
        const result = await reqGetFiles()
        if (result.status === 0) {
            setFileList(result.data)
        }
    }


    //下载
    const handleDownload = async (item) => {
        if (getToken()) {
            if (userAllInfo.role.indexOf('会员') === -1 && item.type === '会员') {
                console.log(1)
                message.warning('该文件需要会员身份才能下载！')
            } else {
                setDownLoadOpen(true)
            }
        } else {
            setLoginOpen(!loginOpen)
        }
    }

    //下载成功
    const downloadOk = ({name, format}) => {
        try {
            setConfirmLoading(true);
            setTimeout(async () => {
                const response = await reqDownLoadFile({filename: name + '.' + format})
                const url = window.URL.createObjectURL(response)
                const link = document.createElement('a')
                link.href = url
                link.setAttribute('download', `${name}.${format}`)
                document.body.appendChild(link)
                link.click()
                link.parentNode.removeChild(link)
                message.success('下载成功!')
                setDownLoadOpen(false)
                setConfirmLoading(false)
            }, 1000)
        } catch (error) {
            setConfirmLoading(false)
            message.success('下载失败!')
        } finally {
            setIsDownloading(false)
        }
    }
    //取消下载
    const downloadCancel = () => {
        setConfirmLoading(false)
        setDownLoadOpen(false);
    };


    //选择文件类型
    const sortChange = (value) => {
        setSortValue(value)
    }


    //文件发生变化时
    const uploadChange = (info) => {
        const {status} = info.file;
        if (status !== 'uploading') {
            console.log(info.file, info.fileList);
        }
        if (status === 'done') {
            message.success(`${info.file.name} 文件上传成功.`);
        } else if (status === 'error') {
            message.error(`${info.file.name} 文件上传失败.`);
        }
        setUploadFileList([...info.fileList]);
    };


    // 上传配置
    const props = {
        name: 'file',
        action: `${process.env.REACT_APP_API_URL}/download/uploads`,
        onChange: uploadChange,
        fileList: uploadFileList,
        beforeUpload(file) {
            const allowedTypes = ['application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/pdf'];
            const isAllowedType = allowedTypes.includes(file.type);
            const isLt6M = file.size / 1024 / 1024 < 6;
            if (!isAllowedType) {
                message.error('只能上传 doc、docx或pdf格式的文件！请更换一个文件!');
            }
            if (!isLt6M) {
                message.error('上传文件大小不能超过 6MB！请更换一个文件!');
            }
            return isAllowedType && isLt6M;
        },
        maxCount: 3,
        onDrop(e) {
            console.log('Dropped files', e.dataTransfer.files);
        },
    };

    //上传文件
    const uploadFile = () => {
        if (getToken()) {
            setOpen(true)
        } else {
            setLoginOpen(!loginOpen)
        }
    }
    //上传文件成功
    const uploadOk = () => {
        setConfirmLoading(true);
        if (uploadFileList.length !== 0) {
            setTimeout(async () => {
                const result = await reqSaveFiles({user_id: userAllInfo.id, files: uploadFileList, sort: sortValue})
                if (result.status === 0) {
                    setOpen(false);
                    setConfirmLoading(false);
                    message.success('文件保存成功！')
                    setUploadFileList([])
                    getData()
                } else {
                    setConfirmLoading(false)
                    message.error('文件保存失败,有重复名字的文件！')
                }

            }, 1000);
        } else {
            message.info('请选择文件')
        }
    }
    const uploadCancel = () => {
        setConfirmLoading(false)
        setUploadFileList([])
        setOpen(false);
    }


    const chooseAll = async () => {
        setIsClick('全部')
        const result = await reqGetFiles()
        setFileList(result.data)
    }

    // 监听 isClick 的变化
    const chooseFree = async () => {
        setIsClick('免费')
        const result = await reqGetFiles();
        setFileList(result.data.filter((item) => item.type.indexOf('免费') !== -1))
    };


    const chooseVip = async () => {
        setIsClick('会员')
        const result = await reqGetFiles()
        setFileList(result.data.filter((item) => item.type.indexOf('会员') !== -1))
    }

    const chooseSort = (label) => {
        setTypeIsClick(label)
        setFileList(fileList)
    }

    const fileItem = (item) => {
        return (
            <div key={item.id} style={{minWidth: '33%'}}>
                <div
                    style={{
                        borderRadius: 20,
                        width: 150,
                        height: 200,
                        marginBottom: 20,
                        backgroundColor: 'rgba(0,0,0,0.06)',
                        display: 'flex',
                        flexDirection: 'column',
                        justifyContent: 'space-between',
                        alignItems: 'center'
                    }}>
                    <img width={60}
                         style={{paddingTop: 10}}
                         src={apiUrl}
                         alt=""/>
                    <div className={classes.Name}>
                        <p>文件名： {item.name}</p>
                    </div>
                    <div>
                        格式：{item.format}
                    </div>
                    <Button
                        style={{marginBottom: 20}}
                        type="primary"
                        disabled={isDownloading && downloadOpen}
                        onClick={() => handleDownload(item)}>
                        {(isDownloading && downloadOpen) ? '下载中...' : '下载'}
                        {loginOpen && <LoginAlert open={loginOpen}/>}
                    </Button>
                    <Modal centered
                           maskStyle={{background: 'rgba(0,0,0,.1)'}}
                           open={downloadOpen}
                           onOk={() => downloadOk({name: item.name, format: item.format})}
                           okText="确认"
                           cancelText="取消"
                           confirmLoading={confirmLoading}
                           onCancel={downloadCancel}>
                        <div style={{fontSize: 20}}>确定要下载这个文件吗？</div>
                    </Modal>
                </div>
            </div>
        )
    }


    return (
        <div className={classes.Container}>
            <div style={{width: '75%'}}>
                <Card>
                    <div style={{
                        minHeight: 80,
                        fontSize: 18,
                        display: 'flex',
                        flexDirection: 'column',
                        justifyContent: 'space-between'
                    }}>
                        <div style={{display: 'flex'}}>
                            <div style={{width: '10%', paddingRight: 20}}>
                                形式
                            </div>
                            <div style={{
                                alignItems: 'center',
                                width: '90%',
                                display: 'flex',
                                fontSize: 18,
                                justifyContent: 'flex-start'
                            }}>
                                <div onClick={chooseAll}
                                     style={{
                                         marginRight: 55,
                                         color: isClick === '全部' ? '#1677ff' : null,
                                         cursor: 'pointer'
                                     }}>全部
                                </div>
                                <div onClick={chooseFree}
                                     style={{
                                         marginRight: 55,
                                         color: isClick === '免费' ? '#1677ff' : null,
                                         cursor: 'pointer'
                                     }}>免费
                                </div>
                                <div onClick={chooseVip}
                                     style={{cursor: 'pointer', color: isClick === '会员' ? '#1677ff' : null,}}>会员
                                </div>
                            </div>
                        </div>
                        <div style={{display: 'flex', marginTop: 20}}>
                            <div style={{width: '10%', paddingRight: 20}}>类型</div>
                            <div
                                style={{
                                    width: '90%',
                                    display: 'flex',
                                    flexWrap: 'wrap',
                                    justifyContent: 'flex-start'
                                }}
                            >
                                {
                                    typeList.map((item) => (
                                        <div key={item.key}
                                             onClick={() => chooseSort(item.label)}
                                             style={{
                                                 minWidth: '16%',
                                                 color: item.label === typeIsClick ? '#1677ff' : '#aaa',
                                                 cursor: 'pointer'
                                             }}>
                                            {/* 将子项的最大宽度设置为容器的三分之一 */}
                                            {item.label}
                                        </div>
                                    ))
                                }
                            </div>
                        </div>
                    </div>
                </Card>
                <Card style={{marginTop: 20, height: 600, overflow: 'auto'}}>
                    <div style={{marginLeft: 50, display: 'flex', justifyContent: 'flex-start', flexWrap: 'wrap'}}>
                        {
                            fileList.filter((item) => {
                                if (typeIsClick === '全部') {
                                    return fileList
                                }
                                return item.sort === typeIsClick
                            }).length === 0 ?
                                <Empty style={{paddingLeft: 200, paddingTop: 150}} description="暂无该类文件"/>
                                :
                                fileList.filter((item) => {
                                    if (typeIsClick === '全部') {
                                        return fileList
                                    }
                                    return item.sort === typeIsClick
                                }).map((item) => (fileItem(item)))
                        }
                    </div>
                </Card>
            </div>
            <div className={classes.Handler}>
                <div className={classes.MyInfo}>
                    <Avatar src={getToken() ? userAllInfo.user_avatar : null} size={64} icon={<UserOutlined/>}/>
                    <span>{userAllInfo.nickname}</span>
                </div>
                <div>
                    <Button onClick={() => uploadFile()} type="primary">
                        上传文件
                        {loginOpen && <LoginAlert open={loginOpen}/>}
                    </Button>
                    <Modal
                        bodyStyle={{width: 650, height: 400}}
                        width={700}
                        title="上传文件"
                        open={open}
                        onOk={uploadOk}
                        confirmLoading={confirmLoading}
                        onCancel={uploadCancel}
                        okText="确认"
                        cancelText="取消"
                    >
                        <div style={{paddingBottom: 10}}>
                            <span>选择文件类型：</span>
                            <Select
                                defaultValue={typeList[1]}
                                style={{width: 120,}}
                                onChange={sortChange}
                                options={typeList.filter(item => item.label !== '全部')}
                            />
                        </div>

                        <Dragger {...props} height={280}>
                            <p className="ant-upload-drag-icon">
                                <InboxOutlined/>
                            </p>
                            <p className="ant-upload-text">点击此处上传文件</p>
                            <p className="ant-upload-hint">
                                或拖拽文件到此处,一次最多上传3个文件
                            </p>
                        </Dragger>
                    </Modal>
                </div>
            </div>
        </div>
    );
};

export default MyDownLoad;